<?php

namespace framework\libraries;

class Stdio
{

    /**
     * Write a string to stdout.
     */
    private static function print($str, $color)
    {
        if (is_array($str) || is_object($str)) {
            $str = json_encode($str);
        }
        $levels = [
            'error' => '31',
            'warning' => '33',
            'info' => '36',
            'success' => '32'
        ];
        $colorCode = $levels[$color] ?? '37';
        $fh = fopen('php://stdout', 'w');
        fwrite($fh, "[" . date("Y-m-d H:i:s") . "] \033[{$colorCode}m{$str}\033[0m\n");
        fclose($fh);
    }

    /**
     * Write a string to stdout with a newline.
     */
    static function println($str, $color = "info")
    {
        self::print($str, $color);
    }

    static function error($str)
    {
        self::print($str . "\n", "error");
    }
}
